package com.chen.service.impl;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.chen.domain.User;
import com.chen.fegin.OAuth2FeignClient;
import com.chen.geetest.GeetestAutoConfiguration;
import com.chen.geetest.GeetestLib;
import com.chen.model.JwtToken;
import com.chen.model.LoginUser;
import com.chen.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.bind.ValidationException;

/**
 * @Author: chen
 * @Date: 2021/4/27 10:17 AM
 * @Version 1.0
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {


    @Autowired
    private GeetestLib geetestLib;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${user.basicToken:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;


    @Override
    public LoginUser login(User loginForm) throws ValidationException {


        LoginUser loginUser = new LoginUser();
        //1.参数校验 【极验】
        GeetestAutoConfiguration.checkGeetest(loginForm, redisTemplate, geetestLib);

        //2.发送远程调用 --》 auth-server
        ResponseEntity<JwtToken> token = oAuth2FeignClient.getToken(
                loginForm.getUsername(),
                loginForm.getPassword(),
                "password",
                "member_type",
                basicToken);
        if (token.getStatusCode() != HttpStatus.OK) {
            throw new ApiException("用户名或密码错误");
        }
        JwtToken body = token.getBody();
        //3.封装返回值【过期redis中的key】
        loginUser.setAccess_token(body.getTokenType() + " " + body.getAccessToken());
        loginUser.setExpire(body.getExpiresIn());
        loginUser.setRefresh_token(body.getRefreshToken());
        loginUser.setUsername(loginForm.getUsername());

        return loginUser;
    }

    @Override
    public LoginUser refreshToken() {

        return null;
    }


}
